<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <!-- <el-form-item :label="USER_TYPE_NAME" prop="username">
        <el-input
          v-model="queryParams.username"
          :placeholder="`请输入${USER_TYPE_NAME}名称`"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属维修店" prop="panId">
        <el-select v-model="queryParams.panId" clearable>
          <el-option
            v-for="item in panList"
            :key="item.id"
            :label="item.username"
            :value="item.panId"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="权限" prop="permissionIds">
        <!-- <el-select
          multiple
          v-model="queryParams.permissionIds"
          clearable
          style="width:300px;"
        >
          <el-option
            v-for="item in authList"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId"
          ></el-option>
        </el-select> -->
        <el-cascader
          v-model="queryParams.permissionIds"
          :options="category"
          :props="props"
          collapse-tags
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-plus" plain size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button plain size="mini" @click="handleSelectAll">全选</el-button>
        <el-button
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
          :disabled="multiple"
          >删除</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(1)"
          >锁定</el-button
        >
        <el-button
          plain
          size="mini"
          :disabled="multiple"
          @click="handleChangeStatus(0)"
          >解锁</el-button
        >
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      ref="table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="55" />
      <el-table-column
        label="用户名"
        align="center"
        prop="username"
        width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="添加时间	"
        align="center"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="权限"
        align="center"
        prop="cmsPermissionList"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.username == "admin"
              ? "所有权限"
              : permissionFormat(scope.row.cmsPermissionList)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="90"
        :formatter="statusFormat"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.username != 'admin'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input
            :disabled="form.id && form.username == 'admin'"
            v-model="form.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="权限" prop="cmsPermissionList">
          <el-tree
            :data="category"
            show-checkbox
            default-expand-all
            node-key="categoryId"
            :props="defaultProps"
            ref="tree"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(false)">保 存</el-button>
        <!-- <el-button type="primary" @click="submitForm(true)">保存并邮件通知</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  addType,
  getType,
  delType,
  updateType,
  changeStatus,
  exportUser
} from "@/api/cms/user";
import { getPage as getCategoryPage } from "@/api/cms/category";

export default {
  name: "Admin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 0,
        permissionIds: []
      },
      // 表单参数
      form: {
        cmsPermissionList: []
      },
      category: [],
      categoryData: [],
      categoryAuth: [],
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      authList: [],
      options: [],
      props: {
        children: "children",
        label: "categoryName",
        value: "categoryId",
        multiple: true
      },
      level2Ids: [],
      formLoading: false
    };
  },
  computed: {
    // 表单校验
    rules() {
      return {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          {
            required: this.form.id ? false : true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ]
        // cmsPermissionList: [
        //   { required: true, message: "请选择权限", trigger: "blur" }
        // ]
      };
    }
  },
  created() {
    getCategoryPage().then(response => {
      this.categoryData = [
        ...response.data
        // { categoryId: -1, categoryName: "考试管理" }
      ];

      const category = this.handleTree(response.data, "categoryId");

      this.category = [
        ...JSON.parse(JSON.stringify(category))
        // { categoryId: -1, categoryName: "考试管理" }
      ];

      this.getList();
    });
  },
  methods: {
    // handleCheckChange(obj, checked, child) {
    //   if (checked) {
    //     if (obj.parentId != 0) {
    //       this.$refs.tree.setChecked(obj.pid, true);
    //     } else {
    //       const children = this.categoryAuth.find(
    //         x => x.categoryId == obj.categoryId
    //       ).children;
    //       const ids = children.map(x => x.categoryId);
    //       const checkedKeys = this.$refs.tree.getCheckedKeys();
    //       if (ids.every(x => checkedKeys.indexOf(x) == -1)) {
    //         children.forEach(item => {
    //           this.$refs.tree.setChecked(item.categoryId, true);
    //         });
    //       }
    //     }
    //     // 如果是子节点  判断父节点是否选中  未选择则选中
    //   } else {
    //     if (obj.parentId == 0) {
    //       this.categoryAuth
    //         .find(x => x.categoryId == obj.categoryId)
    //         .children.forEach(item => {
    //           this.$refs.tree.setChecked(item.categoryId, false);
    //         });
    //     }
    //     // 如果是父节点取消 则全部子节点取消
    //   }
    // },
    permissionFormat(cmsPermissionList) {
      let str = [];
      if (this.categoryData && this.categoryData.length > 0) {
        cmsPermissionList.forEach(item => {
          this.categoryData.forEach(category => {
            if (item.categoryId === category.categoryId) {
              str.push(category.categoryName);
            }
          });
        });
      }
      return str.join(" | ");
    },
    getList() {
      this.loading = true;

      const permissionIds = new Set();
      this.queryParams.permissionIds.forEach(x => {
        x.forEach(y => {
          // if (this.level2Ids.indexOf(y) == -1) {
          permissionIds.add(y);
          // }
          // if (y < 0) {
          //   permissionIds.add(-1 * y);
          // }
        });
      });
      // this.queryParams.permissionIds.forEach(x => {
      //   permissionIds.add(x);
      //   if (x < 0) {
      //     permissionIds.add(-1 * x);
      //   }
      //   const p = this.categoryData.find(y => y.categoryId == x);
      //   console.log(p);
      //   if (p) {
      //     if (p.parentId != 0) {
      //       const p2 = this.categoryData.find(y => y.categoryId == p.parentId);
      //       console.log(p2);
      //       if (p2) {
      //         if (p2.parentId != 0) {
      //           const p3 = this.categoryData.find(
      //             y => y.categoryId == p2.parentId
      //           );
      //           if (p3) {
      //             permissionIds.add(p3.categoryId);
      //           }
      //         } else {
      //           permissionIds.add(p2.categoryId);
      //         }
      //       }
      //     } else {
      //       permissionIds.add(p.categoryId);
      //     }
      //   }
      // });
      // console.log(Array.from(permissionIds));
      listType({
        ...this.queryParams,
        permissionIds: Array.from(permissionIds)
      }).then(response => {
        this.list = response.rows.map(item => {
          item.cmsPermissionText = item.cmsPermissionList.map(
            permission => permission.categoryId
          );
          return item;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    statusFormat(row, column) {
      return row.status == 0 ? "正常" : "锁定";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        username: undefined,
        password: undefined,
        cmsPermissionList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加管理员";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getType(id).then(response => {
        response.data.password = "";
        // const checkedNodes = response.data.cmsPermissionList.filter(
        //   x => x.categoryId
        // );

        this.form = response.data;
        this.form.cmsPermissionList = this.form.cmsPermissionList.map(
          x => x.categoryId
        );
        this.open = true;
        this.title = "修改管理员";
        this.$nextTick(() => {
          setTimeout(() => {
            this.form.cmsPermissionList.forEach(categoryId => {
              this.$refs.tree.setChecked(categoryId, true, false);
            }, 500);
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm: function(send) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const checkedNodes = this.$refs.tree.getCheckedNodes(false, true);

          if (checkedNodes.length == 0) {
            this.$message.error("请选择权限");
            return;
          }

          const cmsPermissionList = checkedNodes.map(x => ({
            categoryId: x.categoryId
          }));
          this.formLoading = true;
          if (this.form.id != undefined) {
            updateType({ ...this.form, cmsPermissionList, type: 0, pan: 1 },send)
              .then(response => {
                this.formLoading = false;
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch(err => {
                this.formLoading = false;
                // this.msgError("用户名已存在");
              });
          } else {
            addType({ ...this.form, cmsPermissionList, type: 0, pan: 1 },send)
              .then(response => {
                this.formLoading = false;
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(err => {
                this.formLoading = false;
                // this.msgError("用户名已存在");
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      if (Ids == 1 || (Array.isArray(Ids) && Ids.indexOf(1) != -1)) {
        this.$message.error("超级管理员不可删除");
        return;
      }
      this.$confirm(`是否确认删除编号为[${Ids}]的管理员?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delType(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm("是否确认导出所有类型数据项?", "警告", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning"
    //   })
    //     .then(function() {
    //       return exportType(queryParams);
    //     })
    //     .then(response => {
    //       this.download(response.msg);
    //     });
    // },
    // 全选
    handleSelectAll() {
      this.$refs.table.toggleAllSelection();
    },
    // 变更状态
    handleChangeStatus(status) {
      if (this.ids == 1 || this.ids.indexOf(1) != -1) {
        this.$message.error("超级管理员不操作");
        return;
      }
      changeStatus({
        ids: this.ids,
        status
      }).then(response => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportUser(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    }
  }
};
</script>
